package com.edu.interceptor;

import com.edu.user.service.ISysUserInfoService;
import com.edu.utils.JsonUtils;
import com.edu.vo.Result;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * <p>title: com.wfx.interceptor</p>
 * author zhuximing
 * description:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysUserInfoService iSysUserInfoService;

    private static ThreadLocal<String> local = new ThreadLocal<>();

    //全局的验证功能
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器");

        //放行请求方法为OPTIONS的请求
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return  true;
        }


        String token = request.getHeader("token");
        if (token == null) {
            //响应客户端
            response(response);
            return false;
        }else{
             //校验令牌
            Result result = iSysUserInfoService.verifyToken(token);
            //获取用户id
            String userId = (String) result.getData();

            if(result.isSuccess()){
                request.setAttribute("userId",userId);
                //将userid存放到threadlocal中

                local.set(userId);
                return  true ; // 放行
            }else{
                response(response);
                return false;
            }
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除threadlocal里面的用户信息
        local.remove();
    }

    private  void  response(HttpServletResponse response) throws  Exception{
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        //响应数据
        Result result = new Result(false,1,"interceptor exception");

        String resultStr = JsonUtils.toString(result);

        writer.write(resultStr);
        writer.close();
    }



    //获取用户id
    public static  String getUserId(){
        return local.get();
    }
}